package Part2_java.util.Map.TreeMap;

import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * ClassName: TreeMapTest
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.04.15 17:16
 */
public class TreeMapTest {

    @Test
    public void test1(){
        TreeMap map = new TreeMap<>();

        map.put("CC",89);
        map.put("BC",89);
        map.put("DX",90);
        try {
            map.put(123,100);
        } catch (ClassCastException e) {
            System.out.println("ClassCastException,不可转型");
        }
        map.put("AA",100);

        //TreeMap按照key值排序
        System.out.println(map);
    }

    @Test
    public void test2(){
        TreeMap map = new TreeMap<>();

        //User类中已经实现了自然排序
        User u1  = new User("HX",52);
        User u2  = new User("SH",26);
        User u3  = new User("CC",27);
        User u4  = new User("AA",26);

        map.put(u4,80);
        map.put(u2,33);
        map.put(u1,12);
        map.put(u3,59);

        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

    @Test
    public void test3(){
        TreeMap map = new TreeMap<>();

        //User1类中实现了自然排序,但只是根据年龄排序，年龄一样的情况没有处理
        User1 u1  = new User1("AA",52);
        User1 u2  = new User1("BB",26);
        User1 u3  = new User1("CC",27);
        User1 u4  = new User1("DD",26);


        map.put(u1,12);
        map.put(u2,33);
        map.put(u3,59);
        map.put(u4,80);//这时候由于u2的年龄和u4一样，所以AA没有进去，但是value值修改了，33———>80

        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

    @Test
    public void test4(){
        TreeMap map = new TreeMap<>(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                //自定义规则：先按姓名字母排序，姓名一样的话年龄大的在前
                if(o1 instanceof User && o2 instanceof User){
                    User u1 = (User) o1;
                    User u2 = (User) o2;
                    if(!u1.getName().equals(u2.getName()))
                        return u1.getName().compareTo(u2.getName());
                    else {
                        if (u1.getAge()!=u2.getAge())
                            return -(u1.getAge()-u2.getAge());
                        else
                            return 0;
                    }
                }
                throw new RuntimeException("类型不匹配");
            }
        });

        //User类中实现了自然排序
        User u1  = new User("AA",52);
        User u2  = new User("BB",26);
        User u3  = new User("BB",27);
        User u4  = new User("DD",26);

        map.put(u1,12);
        map.put(u2,33);
        map.put(u3,59);
        map.put(u4,80);

        for(Object o : map.entrySet()){
            System.out.println(o);
        }


    }
}
